import "DPI-C" function longint axi4_read( input int raddr, input byte rsize);
import "DPI-C" function void axi4_write( input int waddr, input longint wdata, input byte wsize);
module AXI4_memory(
  input clk,
  input rst,

  
  output io_slave_awready,
  input io_slave_awvalid,
  input [31:0] io_slave_awaddr,
  input [3:0] io_slave_awid,
  input [7:0] io_slave_awlen,
  input [2:0] io_slave_awsize,
  input [1:0] io_slave_awburst,

  output io_slave_wready,
  input io_slave_wvalid,
  input [63:0] io_slave_wdata,
  input [7:0] io_slave_wstrb,
  input io_slave_wlast,

  input io_slave_bready,
  output io_slave_bvalid,
  output [1:0] io_slave_bresp,
  output [3:0] io_slave_bid,

  output io_slave_arready,
  input io_slave_arvalid,
  input [31:0] io_slave_araddr,
  input [3:0] io_slave_arid,
  input [7:0] io_slave_arlen,
  input [2:0] io_slave_arsize,
  input [1:0] io_slave_arburst,

  input io_slave_rready,
  output io_slave_rvalid,
  output [1:0] io_slave_rresp,
  output [63:0] io_slave_rdata,
  output io_slave_rlast,
  output [3:0] io_slave_rid


);
  assign io_slave_awready = 1'b1;
  assign io_slave_wready = 1'b1;
  assign io_slave_arready = 1'b1;
  assign io_slave_rlast = 1'b1;
  assign io_slave_bid = 4'b0;
  assign io_slave_bresp = 2'b0;
  assign io_slave_rid = 4'b0;
  assign io_slave_rresp = 2'b0;

  reg [31:0] waddr,raddr;
  reg [63:0] rdata;
  reg bvalid,rvalid;
  localparam CNT_W = 3;
  reg [CNT_W-1:0] cnt;
  reg arvalid;
  reg [2:0] wsize,rsize;
  always @(posedge clk) begin
    if(rst) begin
      waddr <= 32'b0;
      raddr <= 32'b0;
      wsize <= 3'b0;
      rsize <= 3'b0;
      bvalid <= 1'b0;
      rvalid <= 1'b0;
      rdata <= 64'b0;
      cnt <= {CNT_W{1'b0}};
    end else begin
      rdata <= 64'b0;
      cnt <= cnt + {{(CNT_W-1){1'b0}},1'b1};;
      // cnt <= {CNT_W{1'b0}};/*注释此行启用0-7周期随机访存延迟*/
      if(io_slave_bready) bvalid <= 1'b0;
      if(io_slave_wvalid) bvalid <= 1'b1;
      if(io_slave_rready) rvalid <= 1'b0;
      if(io_slave_arvalid) begin 
        arvalid <= 1'b1;
        raddr <= io_slave_araddr;
        rsize <= io_slave_arsize;
      end
      if((arvalid)&&(cnt=={CNT_W{1'b0}})) begin 
        rdata <= axi4_read(raddr,{5'b0,rsize});
        rvalid <= 1'b1;
        arvalid <= 1'b0;
      end
      if(io_slave_awvalid) begin 
        waddr <= io_slave_awaddr;
        wsize <= io_slave_awsize;
      end
      if(io_slave_wvalid) axi4_write(waddr,io_slave_wdata,{5'b0,wsize});
      
      
    end
  end

  assign io_slave_rdata = rdata;
  assign io_slave_rvalid = rvalid;
  assign io_slave_bvalid = bvalid;
endmodule
